package cn.smile.controller.admin;

import java.io.File;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smile.bean.PageBean;
import cn.smile.bean.Result;
import cn.smile.entity.admin.DatabaseBak;
import cn.smile.service.admin.DatabaseBakService;

import javax.annotation.Resource;

/**
 * 数据库备份管理控制器
 */
@Slf4j
@RequestMapping("/admin/database_bak")
@Controller
public class DatabaseBakController {

    @Resource
    private DatabaseBakService databaseBakService;

    @Value("${web.database.backup.dir}")
    private String backUpDir;

    /**
     * 数据库备份文件管理列表页面
     */
    @RequestMapping(value = "/list")
    public String list(Model model, PageBean<DatabaseBak> pageBean) {
        model.addAttribute("title", "备份列表");
        model.addAttribute("pageBean", databaseBakService.findList(pageBean));
        return "admin/database_bak/list";
    }

    /**
     * 数据库备份操作
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> add() {
        databaseBakService.backup();
        return Result.success(true);
    }

    /**
     * 删除备份的记录及文件
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> delete(String ids) {
        if (!StringUtils.isEmpty(ids)) {
            String[] splitIds = ids.split(",");
            for (String id : splitIds) {
                DatabaseBak databaseBak = databaseBakService.find(Long.valueOf(id));
                if (databaseBak != null) {
                    databaseBakService.delete(Long.valueOf(id));
                    File file = new File(databaseBak.getFilepath() + databaseBak.getFilename());
                    if (!file.exists()) {
                        //此时说明文件不存在，按照配置文件的路径重新寻找文件
                        file = new File(backUpDir + databaseBak.getFilename());
                    }
                    boolean delete = file.delete();
                    log.info("删除数据库备份文件完成, delete = {} 备份ID= {}", delete, id);
                }
            }
        }
        return Result.success(true);
    }

    /**
     * 还原数据库文件
     */
    @RequestMapping(value = "restore", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> restore(@RequestParam(name = "id") Long id) {
        databaseBakService.restore(id);
        return Result.success(true);
    }
}
